<?php

namespace app\home\controller;

use think\Validate;
use cmf\controller\HomeBaseController;
use app\home\model\MemberloginModel;

class MemberloginController extends HomeBaseController
{
    public function index(){
        $redirect = $this->request->post("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            $redirect = base64_decode($redirect);
        }
        session('login_http_referer', $redirect);
        if (cmf_is_user_login()) { //已经登录时直接跳到首页
            return redirect(url("home/index/index"));
        } else {
            return $this->fetch(":login");
        }
    } 
    public function doLogin(){
        if($this->request->isPost()){
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32'
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符'
            ]);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $user = new MemberloginModel();
            $log = $user->doMemberLogin($data);
            $session_login_http_referer = session('login_http_referer');
            $redirect = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->success(lang('LOGIN_SUCCESS'), $redirect);
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    break;
                case 2:
                    $this->error('账户不存在');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    break;
                default :
                    $this->error('未受理的请求');
            }
        }else{
            $this->error("请求错误");
        }
    }
    //显示登录用户昵称
    public function memberindex(){
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch();
    }
    /**
     * 退出登录
    */
    public function logout()
    {
        session("user", null);//只有前台用户退出
        return redirect(url("home/memberlogin/index"));
    }
}

